import redis

# HOST = "127.0.0.1"
HOST = "192.168.99.100"
PORT = "6379"
DB = 0
ZSORT_NAME = "sortedTitleSet"
ZLIST_NAME = "bookIdList"
EXIST_FLAG = "aikanFlag"


def set_list():
    """
    列表，适用于建立FIFO等队列。
    :return:
    """
    sr = redis.StrictRedis(host=HOST, port=PORT, db=DB)
    pipe = sr.pipeline()
    sr.delete(ZLIST_NAME)
    sr.set(EXIST_FLAG, "go")
    for idx in range(8001, 10001):
        print(idx)
        pipe.rpush(ZLIST_NAME, idx)
    pipe.execute()


def push_list():
    sr = redis.StrictRedis(host=HOST, port=PORT, db=DB)
    id = sr.lpop(ZLIST_NAME)
    print(" id = "+str(id))
    id = sr.lpop(ZLIST_NAME)
    print(" id = " + str(id))


def set_zsort():
    """
    有序集合，适用于各种排名，按区间取值等情况。
    """
    sr = redis.StrictRedis(host=HOST, port=PORT, db=DB)
    pipe = sr.pipeline()
    for idx in range(2, 10):
        print(idx)
        pipe.zadd(ZSORT_NAME, idx, idx)
    pipe.execute()


def rem_zsort():
    """
    注意一点，如果我们在程序中需要使用redis的返回值，就不能pipeline了，因为pipeline是一起执行的。
    :return:
    """
    sr = redis.StrictRedis(host=HOST, port=PORT, db=DB)
    zsize = sr.zcard(ZSORT_NAME)
    print("zsize=" + str(zsize))
    pipe = sr.pipeline()
    pipe.zrem(ZSORT_NAME, 7)
    pipe.zrem(ZSORT_NAME, 3)
    pipe.execute()
    zsize = sr.zcard(ZSORT_NAME)
    print("zsize=" + str(zsize))
    zscore = sr.zrange(ZSORT_NAME, 0, -1)
    for idx in zscore:
        print(idx)


if __name__ == '__main__':
    test_method = "set_list"
    if test_method == "set_zsort":
        set_zsort()
    elif test_method == "rem_zsort":
        rem_zsort()
    elif test_method == "set_list":
        set_list()
    elif test_method == "push_list":
        push_list()
    print("done, ok")
